package com.ruoyi.web.controller.net;

import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.net.domain.ElementOspfv3;
import com.ruoyi.net.domain.ElementOspfv3PortNeighb;
import com.ruoyi.net.domain.NetElement;
import com.ruoyi.net.netconf.util.DeviceManager;
import com.ruoyi.net.service.INetElementService;
import com.ruoyi.system.service.ISysConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.net.domain.ElementOspfv3Port;
import com.ruoyi.net.service.IElementOspfv3PortService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 网元-OSPFV3接口配置Controller
 * 
 * @author net
 * @date 2024-11-17
 */
@Api(tags = "网元-OSPFV3接口配置")
@RestController
@RequestMapping("/element/ospfv3/port")
public class ElementOspfv3PortController extends BaseController {
    @Autowired
    private IElementOspfv3PortService elementOspfv3PortService;

    @Autowired
    private INetElementService netElementService;

    @Autowired
    private ISysConfigService sysConfigService;

    @Autowired
    private DeviceManager deviceManager;

    /**
     * 查询网元-OSPFV3接口配置列表
     */
    @ApiOperation(value = "查询网元-OSPFV3接口配置列表", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:port:list')")
    @GetMapping("/list")
    public TableDataInfo list(ElementOspfv3Port elementOspfv3Port) {
        startPage();
        List<ElementOspfv3Port> list = elementOspfv3PortService.selectElementOspfv3PortList(elementOspfv3Port);
        return getDataTable(list);
    }

    /**
     * 导出网元-OSPFV3接口配置列表
     */
    @ApiOperation(value = "导出网元-OSPFV3接口配置列表", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:port:export')")
    @Log(title = "网元-OSPFV3接口配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ElementOspfv3Port elementOspfv3Port) {
        List<ElementOspfv3Port> list = elementOspfv3PortService.selectElementOspfv3PortList(elementOspfv3Port);
        ExcelUtil<ElementOspfv3Port> util = new ExcelUtil<ElementOspfv3Port>(ElementOspfv3Port.class);
        util.exportExcel(response, list, "网元-OSPFV3接口配置数据");
    }

    /**
     * 获取网元-OSPFV3接口配置详细信息
     */
    @ApiOperation(value = "获取网元-OSPFV3接口配置详细信息", httpMethod = "GET")
    //    @PreAuthorize("@ss.hasPermi('system:port:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(elementOspfv3PortService.selectElementOspfv3PortById(id));
    }

    /**
     * 新增网元-OSPFV3接口配置
     */
    @ApiOperation(value = "新增网元-OSPFV3接口配置", httpMethod = "POST")
    //    @PreAuthorize("@ss.hasPermi('system:port:add')")
    @Log(title = "网元-OSPFV3接口配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ElementOspfv3Port elementOspfv3Port) {
        return toAjax(elementOspfv3PortService.insertElementOspfv3Port(elementOspfv3Port));
    }

    /**
     * 修改网元-OSPFV3接口配置
     */
    @ApiOperation(value = "修改网元-OSPFV3接口配置", httpMethod = "PUT")
    //    @PreAuthorize("@ss.hasPermi('system:port:edit')")
    @Log(title = "网元-OSPFV3接口配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ElementOspfv3Port elementOspfv3Port) {
        return toAjax(elementOspfv3PortService.updateElementOspfv3Port(elementOspfv3Port));
    }

    /**
     * 删除网元-OSPFV3接口配置
     */
    @ApiOperation(value = "删除网元-OSPFV3接口配置", httpMethod = "DELETE")
    //    @PreAuthorize("@ss.hasPermi('system:port:remove')")
    @Log(title = "网元-OSPFV3接口配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(elementOspfv3PortService.deleteElementOspfv3PortByIds(ids));
    }
    /**
     * 激活设备
     * @param id
     */
    @ApiOperation(value = "激活设备", httpMethod = "GET")
    @GetMapping(value = "/activate/{id}")
    public AjaxResult activateDevice(@PathVariable("id") String id) {
        ElementOspfv3Port entity = elementOspfv3PortService.selectElementOspfv3PortById(id);
        entity.setStatus("1");
        if (sendXml(entity)){
            return toAjax(elementOspfv3PortService.updateElementOspfv3Port(entity));
        }else {
            return AjaxResult.error("激活设备失败");
        }
    }

    /**
     * 去激活设备
     * @param id
     */
    @ApiOperation(value = "去激活设备", httpMethod = "GET")
    @GetMapping(value = "/unactivate/{id}")
    public AjaxResult unactivateDevice(@PathVariable("id") String id) {
        ElementOspfv3Port entity =  elementOspfv3PortService.selectElementOspfv3PortById(id);
        entity.setStatus("0");
        if (sendXml(entity)){
            return toAjax(elementOspfv3PortService.updateElementOspfv3Port(entity));
        }else {
            return AjaxResult.error("去激活设备失败");
        }
    }

    /**
     * 发送xml到设备
     *
     * @param entity
     */
    private boolean sendXml(ElementOspfv3Port entity) {
        boolean isSend = true;
        // TODO: 2024/12/3  设备联调，添加并激活
        if (sysConfigService.selectDebugEnabled()) {
            NetElement netElement = netElementService.getCacheObject(entity.getElementId());
            deviceManager.getDevice(netElement.getIp());

            String operation = "create";
            if ("0".equals(entity.getStatus())) {
                operation = "remove";
            }
            StringBuilder xml = new StringBuilder();
            xml.append("<ospfv3 xmlns=\"http://fiberhome.com/fhnw/yang/ipprotocol/routing/fos-ospfv3\">")
                    .append("    <ospfv3-processes>")
                    .append("      <ospfv3-process>")
                    .append("        <process-id>" + entity.getOspfId() + "</process-id>")
                    .append("        <area>")
                    .append("          <area-id>" + entity.getDomainId() + "</area-id>")
                    .append("          <ospf-interface nc:operation=\"" + operation + "\">")
                    .append("            <if-name>" + entity.getPortName() + "</if-name>")
                    .append("            <instance-id>" + entity.getPortDemo() + "</instance-id>")
                    .append("            <cost>" + entity.getPortCost() + "</cost>")
                    .append("            <dead-interval>" + entity.getKeepTime() + "</dead-interval>")
                    .append("            <network-type>" + entity.getNetType() + "</network-type>")
                    .append("            <dr-priority>" + entity.getLevel() + "</dr-priority>")
                    .append("            <retransmit-interval>" + entity.getRetryInterval() + "</retransmit-interval>")
                    .append("            <transmit-delay>" + entity.getUpdateInterval() + "</transmit-delay>")
                    .append("            <hello-interval>" + entity.getHelloInterval() + "</hello-interval>")
                    .append("            <ipsec-policy>" + entity.getIpsec() + "</ipsec-policy>")
                    .append("            <bfd-ospfv3-if xmlns=\"http://fiberhome.com/fhnw/yang/oam/fos-bfd\">")
                    .append("              <bfd-enable>" + entity.getBfdEnable() + "</bfd-enable>");
//            if (("disable".equalsIgnoreCase(entity.getBfdEnable()) || "0".equalsIgnoreCase(entity.getBfdEnable()))
//                    && !StringUtils.isEmpty(entity.getBfdAttribute()) && entity.getBfdAttribute().split("|").length >= 3) {
//                xml.append("              <min-tx-interval>" + entity.getBfdAttribute().split("|")[0] + "<min-tx-interval>")
//                        .append("              <min-rx-interval>" + entity.getBfdAttribute().split("|")[1] + "<min-rx-interval>")
//                        .append("              <detect-mult>" + entity.getBfdAttribute().split("|")[2] + "<detect-mult>");
//            }
            xml.append("                 </bfd-ospfv3-if>");
            for (ElementOspfv3PortNeighb neighb : entity.getOspfv3NeighborList()) {
                xml.append("                <ospf-neighbor>")
                        .append("               <address>").append(neighb.getIp()).append("</address>") // TODO: 2024/12/3  address是否需要加入mask
                        .append("               <priority>").append(neighb.getLevel()).append("</priority>")
                        .append("               <poll-interval>").append(neighb.getHelloInterval()).append("</poll-interval>")
                        .append("               <cost>").append(neighb.getProtCost()).append("</cost>")
                    .append("               <ospf-neighbor>");
            }
            xml.append("            <mtu-ignore>" + entity.getIgnoreMtu() + "</mtu-ignore>")
                    .append("          </ospf-interface>")
                    .append("        </area>")
                    .append("      </ospfv3-process>")
                    .append("    </ospfv3-processes>")
                    .append("  </ospfv3>");
            System.out.println(xml.toString());
            isSend = deviceManager.editConfig(xml.toString(), "merge");
        }
        return isSend;
    }
}